#include<stdio.h>
#include<string.h>

void rotate1(int* nums, int numsSize, int k)
{
    while(k)
    {
        //最后一个元素存起来, 其他所有元素后移一位
        int tmp = nums[numsSize-1];
        int i = 0;
        for (i = numsSize - 2; i >= 0; i--)
        {
            nums[i+1] = nums[i];
        }
        nums[0] = tmp;
        
        k--;
    }
}

void reverse(int* nums, int start, int end)
{
    while (start < end)
    {
        int tmp = nums[start];
        nums[start] = nums[end];
        nums[end] = tmp;

        start++;
        end--;
    }
}

void rotate2(int* nums, int numsSize, int k)
{
    //避免end为负值造成越界访问
    if (k > numsSize)
    {
        k %= numsSize;
    }
    //旋转次数等于数组长度的时候不需要变化了
    if (k == numsSize)
    {
        goto end;
    }

    reverse(nums, 0, numsSize - k - 1);
    reverse(nums, numsSize - k, numsSize - 1);
    reverse(nums, 0, numsSize - 1);

    end:;
}

void rotate3(int* nums, int numsSize, int k)
{
    if (k > numsSize)
    {
        k %= numsSize;
    }
    if (k == numsSize)
    {
        goto end;
    }
 
    int* arr = (int*)malloc(sizeof(int) * numsSize);
    
    memmove(arr, nums + numsSize - k, k * sizeof(int));
    memmove(arr + k, nums, (numsSize - k) * sizeof(int));
    memmove(nums, arr, numsSize * sizeof(int));
 
    free(arr);
    arr = NULL;
 
    end:;  
}

void Print(int* nums, int numsSize)
{
    int i = 0;
    for (i = 0; i < numsSize; i++)
    {
        printf("%d ", nums[i]);
    }
}

int main()
{
    int nums[1] = {1};
    int k = 4;
    int numsSize = sizeof(nums) / sizeof(nums[0]);

    //rotate1(nums, numsSize, k);
    //rotate2(nums, numsSize, k);
    rotate3(nums, numsSize, k);

    Print(nums, numsSize);

    return 0;
}